package com.heima.wemedia.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.heima.api.feign.ApArticleFeignClient;
import com.heima.audit.baidu.BaiduImageScan;
import com.heima.audit.baidu.BaiduTextScan;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.functors.InstantiateTransformer;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;
import java.security.PrivateKey;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 自媒体文章自动审核
 *
 * @Author wd
 * @Date 2025/6/27 20:20
 */
@Slf4j
@Service
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Resource
    private WmNewsMapper wmNewsMapper;
    @Resource
    private BaiduImageScan baiduImageScan;
    @Resource
    private BaiduTextScan baiduTextScan;
    @Resource
    private FileStorageService fileStorageService;




    /**
     * 自媒体文章审核
     *
     * @param id 自媒体文章id
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void autoScanMediaNews(Integer id) {
        // 根据自媒体文章id查询文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null){
            throw new RuntimeException("文章不存在");
        }
        // 判断文章status
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){
            // 提取文章中的文本内容与图片
            Map<String,Object> textAndImages = handleTextAndImages(wmNews);

            // 审核文本内容
//            Integer contentScan = baiduTextScan.textScan((String) textAndImages.get("content"));
//            if (contentScan==2){
//                wmNews.setStatus(contentScan.shortValue());
//                wmNews.setReason("当前文章中存在违规内容");
//                wmNewsMapper.updateById(wmNews);
//                return;
//            } else if (contentScan == 3){
//                wmNews.setStatus(contentScan.shortValue());
//                wmNews.setReason("当前文章中存在违规内容");
//                wmNewsMapper.updateById(wmNews);
//            }
            boolean isTextScan = handleTextScan((String) textAndImages.get("content"),wmNews);
            if(!isTextScan)return;

            // 审核图片内容
            boolean isImageScan =  handleImageScan((List<String>) textAndImages.get("images"),wmNews);
            if(!isImageScan)return;

            // 文本和图片都审核通过，保存到app端文章
            ResponseResult responseResult =saveAppArticle(wmNews);
            if(!responseResult.getCode().equals(200)){
                throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核，保存app端相关文章数据失败");
            }
            //回填article_id
            wmNews.setArticleId((Long) responseResult.getData());
            updateWmNews(wmNews,(short) 9,"审核成功");

        }
    }

    private void updateWmNews(WmNews wmNews, short i, String 审核成功) {
    }

    private boolean handleTextScan(String content, WmNews wmNews) {

        boolean flag = true;

        if((wmNews.getTitle()+""+content).length() == 0){
            return flag;
        }

        try {
            Integer  res =baiduTextScan.textScan((wmNews.getTitle()+"-"+content));
            if(res != null){
                //审核失败
                if(res==2){
                    flag = false;
                    updateWmNews(wmNews, (short) 2, "当前文章文本中存在违规内容");
                }

                //不确定信息  需要人工审核
                if(res==3){
                    flag = false;
                    updateWmNews(wmNews, (short) 3, "当前文章文本疑似违规，需要人工审核");
                }
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }


    /**
     * 审核图片
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImageScan(List<String> images, WmNews wmNews) {

        boolean flag = true;

        if(images == null || images.size() == 0){
            return flag;
        }

        //下载图片 minIO
        //图片去重
        images = images.stream().distinct().collect(Collectors.toList());

        List<byte[]> imageList = new ArrayList<>();

        for (String image : images) {
            byte[] bytes = fileStorageService.downLoadFile(image);
            imageList.add(bytes);
        }


        //审核图片
        try {
            for (byte[] img : imageList) {
                Integer res = baiduImageScan.imageScan(img);
                //审核失败
                if(res.equals("不合规")){
                    flag = false;
                    updateWmNews(wmNews, (short) 2, "当前文章图片审核失败");
                }

                //不确定信息  需要人工审核
                if(res.equals("疑似")) {
                    flag = false;
                    updateWmNews(wmNews, (short) 3, "当前文章图片疑似违规，需要人工审核");

                }
            }
//            String res = baiduImageScan(imageList);
//            if(res != null){
//                //审核失败
//                if(res.equals("不合规")){
//                    flag = false;
//                    updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容");
//                }
//
//                //不确定信息  需要人工审核
//                if(res.equals("疑似")){
//                    flag = false;
//                    updateWmNews(wmNews, (short) 3, "当前文章中存在不确定内容");
//                }
//            }

        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }


    private Map<String, Object> handleTextAndImages(WmNews wmNews) {

        //存储纯文本内容
        StringBuilder stringBuilder = new StringBuilder();

        List<String> images = new ArrayList<>();

        //1。从自媒体文章的内容中提取文本和图片
        if(StringUtils.isNotBlank(wmNews.getContent())){
            List<Map> maps = JSONArray.parseArray(wmNews.getContent(), Map.class);
            for (Map map : maps) {
                if (map.get("type").equals("text")){
                    stringBuilder.append(map.get("value"));
                }

                if (map.get("type").equals("image")){
                    images.add((String) map.get("value"));
                }
            }
        }
        //2.提取文章的封面图片
        if(StringUtils.isNotBlank(wmNews.getImages())){
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("content",stringBuilder.toString());
        resultMap.put("images",images);
        return resultMap;

    }

    @Resource
    private ApArticleFeignClient  articleClient;

    @Resource
    private WmChannelMapper wmChannelMapper;

    @Resource
    private WmUserMapper wmUserMapper;

    /**
     * 保存app端相关的文章数据
     * @param wmNews
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {

        ArticleDto dto = new ArticleDto();
        //属性的拷贝
        BeanUtils.copyProperties(wmNews,dto);
        //文章的布局
        dto.setLayout(wmNews.getType());
        //频道
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if(wmChannel != null){
            dto.setChannelName(wmChannel.getName());
        }

        //作者
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if(wmUser != null){
            dto.setAuthorName(wmUser.getName());
        }

        //设置文章id
        if(wmNews.getArticleId() != null){
            dto.setId(wmNews.getArticleId());
        }
        dto.setCreatedTime(new Date());

        ResponseResult responseResult = articleClient.save(dto);
        return responseResult;
    }



}
